package com.bella.api.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;

/**
 * 密码加密相关
 * 
 * @author lanjiamian
 */
public final class PasswordUtil {

  private static final Logger logger = LoggerFactory.getLogger(PasswordUtil.class);

  private static final String DEFAULT_HASH_ALGORITHM = "MD5";

  private static final String LAWSON_SALT_KEY = "2517e44b078b0e5e22f305decc856ccc";

  private static final String DEFAULT_APP_SIGNATURE = "Yoren2016";

  private PasswordUtil() {
  }

  public static String getSignature(String input) {
    return getMD5(input, DEFAULT_APP_SIGNATURE, DEFAULT_HASH_ALGORITHM);
  }

  public static String getDigest(String input) {
    return getMD5(input, LAWSON_SALT_KEY, DEFAULT_HASH_ALGORITHM);
  }

  public static String getMD5(String input, String salt, String algorithm) {
    String s = null;
    String source = input + salt;
    char hexDigits[] = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
    try {
      MessageDigest md5 = MessageDigest.getInstance(algorithm);
      md5.update(source.getBytes());
      byte tmp[] = md5.digest();
      char str[] = new char[16 * 2];
      int k = 0;
      for (int i = 0; i < 16; i++) {
        byte byte0 = tmp[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
      }
      s = new String(str);

    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return s;
  }

  /**
   * AEON 密码加密
   * 
   * @param source
   * @return
   */
  public static String getMD5(String source) {
    String s = null;
    char hexDigits[] = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
    try {
      MessageDigest md5 = MessageDigest.getInstance("MD5");
      md5.update(source.getBytes());
      byte tmp[] = md5.digest();
      char str[] = new char[16 * 2];
      int k = 0;
      for (int i = 0; i < 16; i++) {
        byte byte0 = tmp[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
      }
      s = new String(str);

    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return s;
  }
}
